set +x
EnvName={{.EnvName}}
ServiceName={{.ServiceName}}

DeployHost={{.DockerLabel}}
MainDomain={{.MainDomain}} # in nginx, the server_name
SubDomain={{.SubDomain}} # in nginx, the server_name

OutPort={{.Port}}
DockerVolumeRoot={{.DocVolume}}

BackendServiceName={{.BackendServiceName}}
BackendStaticVolume={{.BackendStaticVolume}}
BackendPubMediaVolume={{.BackendPubMediaVolume}}

DockerNetwork={{.DockerNetwork}}
DockerRepository={{.DockerRepository}}  #10.110.0.11:5000
DockerManagerHost={{.DockerManagerHost}} #g-node1  # g-node1
DockerManagerUser={{.DockerManagerUser}} #g-node1  # g-node1
DockerManagerPort={{.DockerManagerPort}} #7111
DockerBuildResourceRoot={{.DockerBuildResourceRoot}}
DockerReserveMemory=3GB

set -eu;set -o pipefail
# below lines is from jenkins var
BranchNameV1=$V1_Version
BranchNameV2=$V2_Version
ForceUpdate=$should_update_nginx_config

GitV1='git@github.com:xxxxx/sddkccom.git'
GitV2='git@github.com:xxxxxxx/sssnext.git'
ProjectName1=$(basename "$GitV1"| cut -d . -f 1)
ProjectName2=$(basename "$GitV2"| cut -d . -f 1)
ProjectSubFolder1=build
ProjectSubFolder2=v2

FrontendServerRoot=/opt/karbon_app
BackendStatic=$FrontendServerRoot/backend_collectstatic
BackendPubMedia=$FrontendServerRoot/backend_share/pub_media

BuildRootDir="/opt/karbon_build"
BuildWorkDir=$BuildRootDir/$EnvName/customer_portal_build
BuildTempDir=$BuildWorkDir/docker_temp_dir


DockerImageName=${EnvName}_customerportal:latest
# django static collection dst folder, will be served by nginx
NginxConfigName=customer_portal_nginx.conf
NginxTemplateFile=$DockerBuildResourceRoot/$NginxConfigName.template

changeNginxConfig () {
  sed -i 's/{.BackendServiceName}/'"$BackendServiceName"'/g' "$1"
  sed -i 's/{.SubDomain}/'"$SubDomain"'/g' "$1"
  sed -i 's/{.MainDomain}/'"$MainDomain"'/g' "$1"
}

# build for v1 or v2
# $1: mark for 1 or 2, $2: branch_name
doBuild () {
  branch_name=$2
  case "$1" in
    "1" )
    git=$GitV1
    project_name=$ProjectName1
    project_build_out=build
    is_new_version="no"
    frontend_subfolder=$ProjectSubFolder1
    npm_build_cmd="build:release";;
    "2" )
    git=$GitV2
    project_name=$ProjectName2
    project_build_out=build
    is_new_version="yes"
    frontend_subfolder=$ProjectSubFolder2
    npm_build_cmd="build";;
  esac

  docker_vol=$DockerVolumeRoot/$frontend_subfolder
  if [[ ! -d "$docker_vol" ]]; then sudo mkdir -p "$docker_vol"; fi

  cd "$BuildWorkDir"
  if [[ ! -d "$project_name" ]]; then
    git clone "$git"
  fi

  cd "$project_name"

  git checkout -f
  git fetch
  if [[ "${branch_name:0:1}" == "v" ]]; then
    git checkout "$branch_name"
  else
    git checkout "$branch_name"
    git reset --hard "origin/$branch_name"
  fi

  # for npm
  export PATH=$PATH:/usr/local/node/bin
  export http_proxy="http://127.0.0.1:8118";export https_proxy="http://127.0.0.1:8118";
  # npm --registry="https://registry.npm.taobao.org" install;
  npm install

  # export NODE_ENV=development;
  export VUE_APP_DISABLE_SENTRY=yes;
  export VUE_APP_EKYC=on
  if [[ "$is_new_version" == "yes" ]]; then
    export PUBLIC_URL=/v2
  fi
  npm run $npm_build_cmd

  # copy build out content
  sudo cp -a $project_build_out/* $docker_vol/
}

echo "=== going to deploy v1 version: $BranchNameV1"
echo "=== going to deploy v1 version: $BranchNameV2"
if [[ ! -d "$BuildRootDir" ]]; then mkdir -p "$BuildRootDir"; fi
if [[ ! -d "$BuildTempDir" ]]; then mkdir -p "$BuildTempDir"; fi

if [[ "X$BranchNameV1" != "X" ]]; then
  doBuild 1 "$BranchNameV1"
fi
if [[ "X$BranchNameV2" != "X" ]]; then
  doBuild 2 "$BranchNameV2"
fi

# check if service is already exists
if ssh -p $DockerManagerPort $DockerManagerUser@$DockerManagerHost sudo docker service ls |grep $ServiceName; then
  if [[ "$ForceUpdate" != "yes" ]]; then
    echo "frontend files updated"
    exit 0
  fi
fi

# copy nginx config file to docker build folder
if [[ ${#BuildTempDir} -gt 20 ]];then
	rm -rf ${BuildTempDir:?}/*
else
	echo "to delete '$BuildTempDir' is dangerous"
    exit 1
fi

cp $NginxTemplateFile "$BuildTempDir/$NginxConfigName"
# change NginxConfig content
changeNginxConfig "$BuildTempDir/$NginxConfigName"

# do docker build
# delete old docker image with same name
# set +o pipefail
# sudo docker image ls | grep "${DockerImageName%%:*}" |sort  | awk '{print $1":"$2}' | xargs -r docker image rm
# set -o pipefail

# build docker image
echo "=== building docker: $DockerImageName"
sudo docker build --no-cache --rm --force-rm -t "$DockerImageName" -f- "$BuildTempDir" <<EOF

FROM nginx:1.17.9
COPY ./$NginxConfigName /etc/nginx/conf.d/
EXPOSE 80
EOF

echo "=== finish build of docker: $DockerImageName"

# push to image to the registry
sudo docker tag "$DockerImageName" "$DockerRepository/$DockerImageName"
sudo docker push "$DockerRepository/$DockerImageName"
sudo docker image rm "$DockerImageName"

if [[ $DeployHost == "" ]]; then
  ssh -p $DockerManagerPort $DockerManagerUser@$DockerManagerHost \
    sudo docker service rm $ServiceName\; \
    sudo docker service create --reserve-memory=$DockerReserveMemory \
    --name $ServiceName \
    --network $DockerNetwork \
    --publish $OutPort:80 \
    --mount type=bind,source=$BackendStaticVolume,destination=$BackendStatic \
    --mount type=bind,source=$BackendPubMediaVolume,destination=$BackendPubMedia \
    --mount type=bind,source=$DockerVolumeRoot/$ProjectSubFolder1,destination="$FrontendServerRoot/$ProjectName1/$ProjectSubFolder1" \
    --mount type=bind,source=$DockerVolumeRoot/$ProjectSubFolder2,destination="$FrontendServerRoot/$ProjectName2/$ProjectSubFolder2" \
    "$DockerRepository/$DockerImageName"
else
  ssh -p $DockerManagerPort $DockerManagerUser@$DockerManagerHost \
    sudo docker service rm $ServiceName\; \
    sudo docker service create --reserve-memory=$DockerReserveMemory \
    --name $ServiceName \
    --network $DockerNetwork \
    --publish $OutPort:80 \
    --mount type=bind,source=$BackendStaticVolume,destination=$BackendStatic \
    --mount type=bind,source=$BackendPubMediaVolume,destination=$BackendPubMedia \
    --mount type=bind,source=$DockerVolumeRoot/$ProjectSubFolder1,destination="$FrontendServerRoot/$ProjectName1/$ProjectSubFolder1" \
    --mount type=bind,source=$DockerVolumeRoot/$ProjectSubFolder2,destination="$FrontendServerRoot/$ProjectName2/$ProjectSubFolder2" \
    --constraint node.labels.khost==$DeployHost \
    "$DockerRepository/$DockerImageName"
fi

